
import config from '@/config'
import { toLogin } from '@/utils/utils'

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = config.apiBaseUrl,
		header = config.header;
	let token = uni.getStorageSync('token')
	if (!noAuth) {
		//登录过期自动登录
		if (!token) {
			toLogin();
			token = uni.getStorageSync('token')
		}
	}
	
	if (token) header['Authorization'] = token;
	

	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + '/api/' + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			timeout: config.timeout,
			success: (res) => {
				if (noVerify)
					reslove(res.data, res);
				else if (res.data.code == 200)
					reslove(res.data, res);
				else if (res.data.code == 400) {
					uni.showModal({
						title: '提示',
						content: res.data.message,
						showCancel: false,
						success: () => {
							reject(res.data);
						}
					})
				}
				else if ([403].indexOf(res.data.code) !== -1) {
					toLogin();
					reject(res.data);
				} else
					reject(res.data.message || (`系统错误`));
			},
			fail: (msg) => {
				let data = {
					mag: (`请求失败`),
					status: 1 //1没网
				}
				// #ifdef APP-PLUS
				reject(data);
				// #endif
				// #ifndef APP-PLUS
				reject((`请求失败`));
				// #endif
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;